package com.fingard.dsp.bank.directbank.pab01;

import java.util.Calendar;
import java.util.Date;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.ITransaction;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7515TodayTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7516HisTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.RetAtsTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.detail.RetAtsTransDetail;
import com.fingard.text.StringHelper;
import com.fingard.util.DateHelper;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

public class PAB01Transaction extends PAB01Base implements ITransaction {
    public RetAtsTrans d_7516_HisTrans(Req7516HisTrans p_req7516) throws Exception {
        RetAtsTrans retAts = new RetAtsTrans(p_req7516.reqHeader);
        retAts.writeStart();
        String tmpRespCode = "";
        String tmpRespInfo = "";
        try {
            Calendar tmpCalendarFrom = Calendar.getInstance();
            tmpCalendarFrom.setTime(p_req7516.getDateFrom());

            Calendar tmpCalendarTo = Calendar.getInstance();
            tmpCalendarTo.setTime(p_req7516.getDateTo());

            int tmpIntDateFrom = 0;
            int tmpIntDateTo = 0;

            // 按天查询
            while (tmpIntDateFrom <= tmpIntDateTo) {
                Calendar tmpClndrStepTo = Calendar.getInstance();
                tmpClndrStepTo.setTime(tmpCalendarFrom.getTime());

                // 判断是否跨月
                if (DateHelper.compareMonth(tmpCalendarFrom, tmpCalendarTo) == -1) {
                    // 跨月则设置为月末
                    tmpClndrStepTo.set(Calendar.DAY_OF_MONTH, tmpClndrStepTo.getActualMaximum(Calendar.DAY_OF_MONTH));
                } else {
                    tmpClndrStepTo.setTime(tmpCalendarTo.getTime());
                }

                PAB01Header bankHeader = new PAB01Header();
                bankHeader.trncode = "4013";
                bankHeader.fourZero = "0000";
                bankHeader.reqSeqNo = getQryTransID();

                String endFlag = "";
                String pageNo = "";
                int pageCount = 1;

                do {
                    endFlag = "";
                    pageNo = String.format("%6s", pageCount).replace(" ", "0");

                    XmlTextWriter xmlWriter = new XmlTextWriter();
                    xmlWriter.autoFormat = false;
                    writeCommonHeader(xmlWriter);
                    xmlWriter.writeStartElement("Result");
                    xmlWriter.writeElementString("AcctNo", p_req7516.actNum);
                    xmlWriter.writeElementString("CcyCode", convertCurToBank(p_req7516.actCur));
                    xmlWriter.writeElementString("BeginDate", Format.Date8Format.format(tmpCalendarFrom.getTime()));
                    xmlWriter.writeElementString("EndDate", Format.Date8Format.format(tmpClndrStepTo.getTime()));
                    xmlWriter.writeElementString("PageNo", pageNo);
                    
                    boolean OrderMode = getBankConfig().getValueAsBool("OrderMode");
                    if(OrderMode){
                    	xmlWriter.writeElementString("OrderMode", "001");
                    }else{
                        xmlWriter.writeElementString("OrderMode", "002");
                    }

                    String pageSize = getBankConfig().getValueAsString("eachPageSize");
                    if (StringHelper.isNullOrEmpty(pageSize)) {
                        pageSize = "100";
                    }
                    WriteBankLogLn("eachPageSize:" + pageSize);
                    xmlWriter.writeElementString("PageSize", pageSize);
                    xmlWriter.writeElementString("Reserve", "");
                    xmlWriter.writeEndElement();
                    xmlWriter.writeEndDocument();

//                    String[] tmpStrRet = sendToBank(xmlWriter.toXmlString(), bankHeader);
                    String[] tmpStrRet = sendToBank(xmlWriter.toXmlString(),bankHeader,p_req7516.reqHeader.transType, p_req7516.reqHeader.commandCode);

                    if (tmpStrRet[0].length() == 0) {
                        if (StringHelper.hasAnyChar(tmpStrRet[1])) {
                            byte[] retBytes = tmpStrRet[1].getBytes(getCharset());
                            String retCode = new String(retBytes, 87, 6, getCharset());
                            String retInfo = new String(retBytes, 93, 100, getCharset()).trim();

                            if ("000000".equals(retCode)) {
                                if (tmpStrRet[1].contains("<")) {
                                    StringBuilder tmpSbMsg = new StringBuilder();
                                    XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1].substring(tmpStrRet[1].indexOf("<")), tmpSbMsg);
                                    if (tmpBkReader != null) {
                                        tmpRespCode = "0";
                                        tmpRespInfo = retInfo.substring(2);
                                        endFlag = tmpBkReader.getFirstText("/Result/EndFlag");

                                        while (tmpBkReader.read("/Result/list")) {
                                            RetAtsTransDetail tmpRetDetail = new RetAtsTransDetail();
                                            XElement tmpRetNode = tmpBkReader.readedXElement;

                                            tmpRetDetail.actNum = tmpRetNode.getSingleTextNotNull("AcctNo").trim();

                                            tmpRetDetail.tranDate = DateHelper.getFormat12Date(tmpRetNode.getSingleText("AcctDate"));// 格式yyyy-MM-dd
                                            tmpRetDetail.tranTime = tmpRetDetail.tranDate + " " + DateHelper.getFormat8Time(tmpRetNode.getSingleText("TxTime"));// 格式"yyyy-MM-dd HH:mm:ss"
                                            tmpRetDetail.valueDate = tmpRetDetail.tranDate;
                                            tmpRetDetail.tranAmt = tmpRetNode.getSingleText("TranAmount");
                                            tmpRetDetail.accBal = tmpRetNode.getSingleText("AcctBalance");
                                            //tmpRetDetail.cdFlag = (tmpRetNode.getSingleText("DcFlag").equals("C")) ? ("1"): ("2");
                                            String bkDcFlag = tmpRetNode.getSingleText("DcFlag");
                                            if ("C".equals(bkDcFlag)) {
                                                tmpRetDetail.cdFlag = "2";
                                                tmpRetDetail.recAccNum = tmpRetNode.getSingleTextNotNull("OutAcctNo").trim();
                                                tmpRetDetail.recAccName = tmpRetNode.getSingleTextNotNull("OutAcctName").trim();
                                                tmpRetDetail.recAccBank = tmpRetNode.getSingleTextNotNull("OutBankName").trim();
                                                if (StringHelper.isNullOrEmpty(tmpRetDetail.recAccBank)) {
                                                    tmpRetDetail.recAccBank = tmpRetNode.getSingleTextNotNull("OutBankNo").trim();
                                                }

                                            } else if ("D".equals(bkDcFlag)) {
                                                tmpRetDetail.cdFlag = "1";
                                                tmpRetDetail.recAccNum = tmpRetNode.getSingleTextNotNull("InAcctNo").trim();
                                                tmpRetDetail.recAccName = tmpRetNode.getSingleTextNotNull("InAcctName").trim();
                                                tmpRetDetail.recAccBank = tmpRetNode.getSingleTextNotNull("InBankName").trim();
                                                if (StringHelper.isNullOrEmpty(tmpRetDetail.recAccBank)) {
                                                    tmpRetDetail.recAccBank = tmpRetNode.getSingleTextNotNull("InBankNo").trim();
                                                }
                                               // tmpRetDetail.receiptNo = tmpRetNode.getSingleTextNotNull("TranSeqNo").trim();

                                            } else {
                                                tmpRespCode = "-1";
                                                tmpRespInfo = "借贷标志有误，值：" + bkDcFlag;
                                                break;
                                            }

                                            if (tmpRetDetail.tranAmt.startsWith("-")) {
                                                if ("2".equals(tmpRetDetail.cdFlag)) {
                                                    tmpRetDetail.cdFlag = "1";
                                                } else {
                                                    tmpRetDetail.cdFlag = "2";
                                                }
                                                tmpRetDetail.tranAmt = StringHelper.trimStart(tmpRetDetail.tranAmt, "-");
                                            }

                                            tmpRetDetail.usage = tmpRetNode.getSingleTextNotNull("Purpose").trim();
                                            tmpRetDetail.comment = tmpRetNode.getSingleTextNotNull("AbstractStr").trim() + tmpRetNode.getSingleTextNotNull("AbstractStr_Desc").trim();
                                            tmpRetDetail.abstr = pickupAbstr(tmpRetNode.getSingleTextNotNull("Reserve"), tmpRetDetail.usage, tmpRetDetail.comment);
                                            tmpRetDetail.payCode = tmpRetNode.getSingleTextNotNull("VoucherNo").trim();
                                            tmpRetDetail.cur = convertCurToATS(tmpRetNode.getSingleText("CcyCode"));
                                            //tmpRetDetail.receiptNo = tmpRetNode.getSingleTextNotNull("HostTrace").trim();
                                            //tmpRetDetail.busRef = tmpRetNode.getSingleTextNotNull("TranSeqNo").trim();
                                            //tmpRetDetail.bnkSeqNo = tmpRetNode.getSingleTextNotNull("BussSeqNo").trim();
                                            /*if(StringHelper.isNullOrEmpty(tmpRetDetail.receiptNo)){
                                            	tmpRetDetail.receiptNo = tmpRetDetail.bnkSeqNo;
                                            }*/
                                            //String hostTrace=tmpRetNode.getSingleTextNotNull("HostTrace").trim();//银行记账流水号
                                            //String accountDate=tmpRetNode.getSingleTextNotNull("AcctDate").trim();//记账日期
                                            //String detailSerialNo=tmpRetNode.getSingleTextNotNull("DetailSerialNo").trim();//明细序号
                                            //tmpRetDetail.originator=hostTrace+accountDate+detailSerialNo;//回单匹配号 匹配规则：银行记账流水号+记账日期+明细序号
                                            //调整
                                            tmpRetDetail.busRef = tmpRetNode.getSingleTextNotNull("HostTrace").trim();//业务参考号
                                            tmpRetDetail.bnkSeqNo = tmpRetNode.getSingleTextNotNull("BussSeqNo").trim();//银行交易流水号
                                            tmpRetDetail.originator=tmpRetNode.getSingleTextNotNull("HostTrace").trim();//银行记账流水号
                                            //3240792006121900479941EBK(交易金额),3240792006121900479941FEE(对应交易手续费)
                                            String abstractStr = tmpRetNode.getSingleTextNotNull("AbstractStr").trim();
                                            tmpRetDetail.receiptNo = tmpRetDetail.originator + abstractStr;

                                            nodeAnalysic(tmpBkReader.readedXElement, tmpRetDetail, getCharset());

                                            retAts.writeRetDetail(tmpRetDetail);
                                        }

                                        pageCount++;
                                        bankHeader.fourZero = String.valueOf(1000 + pageCount);

                                    } else {
                                        tmpRespCode = "-1";
                                        tmpRespInfo = tmpSbMsg.toString();
                                    }
                                } else {
                                    tmpRespCode = "-1";
                                    tmpRespInfo = "银行返回报文格式非法";
                                }
                            } else {
                                tmpRespCode = "ES0200".equals(retCode) ? "0" : "-1";//ES0200:查询结果为空
                                tmpRespInfo = retInfo.trim();
                            }
                        } else {
                            tmpRespCode = "-1";
                            tmpRespInfo = "银行响应内容为空";
                        }
                    } else {
                        tmpRespCode = "-1";
                        tmpRespInfo = tmpStrRet[1];
                    }
                } while ("N".equals(endFlag));

                tmpCalendarFrom = tmpClndrStepTo;
                tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);
                tmpIntDateFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
                tmpIntDateTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            tmpRespCode = "-1";
            tmpRespInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }

        if ("-1".equals(tmpRespCode)) {
            retAts.writeRespCode(tmpRespCode);
            retAts.writeRespInfo(tmpRespInfo);
        } else if (retAts.getWrittenRdCount() == 0) {
            retAts.writeRespCode("0");
            retAts.writeRespInfo("交易为空");
        }

        retAts.writeEnd();
        return retAts;
    }

    public RetAtsTrans d_7515_TodayTrans(Req7515TodayTrans p_req7515) throws Exception {
        Req7516HisTrans tmpReq7516 = new Req7516HisTrans(p_req7515.reqHeader);

        tmpReq7516.actArea = p_req7515.actArea;
        tmpReq7516.actCur = p_req7515.actCur;
        tmpReq7516.actNum = p_req7515.actNum;

        String tmpStrToday = Format.Date8Format.format(new Date());
        tmpReq7516.dateFrom = tmpStrToday;
        tmpReq7516.dateTo = tmpStrToday;

        return d_7516_HisTrans(tmpReq7516);
    }
}
